package com.smforj.ssm.modules.wc.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.smforj.ssm.frame.core.enums.RouterMapping;
import com.smforj.ssm.frame.core.enums.SessionC;
import com.smforj.ssm.frame.core.utils.StringEx;
import com.smforj.ssm.frame.core.web.controller.BaseControllerSupportImpl;
import com.smforj.ssm.frame.core.web.domain.DataResult;
import com.smforj.ssm.frame.core.web.domain.DataResult.DataStatus;
import com.smforj.ssm.modules.lib.domain.LoginUser;
import com.smforj.ssm.modules.lib.domain.SysReader;
import com.smforj.ssm.modules.lib.domain.SysReaderWechat;
import com.smforj.ssm.modules.lib.service.ReaderWechatService;
import com.smforj.ssm.modules.sys.service.SysReaderService;
import com.smforj.ssm.modules.wc.service.BusinessService;
import com.smforj.ssm.modules.wc.util.JsapiUtil;

/***
 * 公共操作Controller
 * 针对微信提供 注册功能
 * 
 * @author Haijun Gao 
 * @date 2016-8-11 下午2:00:54
 * @desp http://www.cnblogs.com/saga5998/
 * @email 573107773@qq.com
 */
@RouterMapping("/ssr/sys/book/")
@Controller
@RequestMapping("/wechat/book")  
public class BusinessController extends BaseControllerSupportImpl {
	
	private Logger log = Logger.getLogger(this.getClass());
	
	@Autowired
	private ReaderWechatService readerWechatService;
	@Autowired
	private SysReaderService sysReaderService; 
	@Autowired
	@Qualifier("esbusinessService")
	private BusinessService businessService;   

	/***
	 * 跳转到查询界面
	 * @return "opQSRwWhh9sCHQejRW4V8SlhkFNI";//
	 * @date 2016-8-11 下午2:03:45
	 */
	@RequestMapping(value={"/query"},method = RequestMethod.GET)
	public ModelAndView doquery(HttpServletRequest request,@RequestParam(required=false) String uid)
	{   
		 Map<String,Object> map = new HashMap<String,Object>(); 
		try{
			//没有request 参数就从session中获取 
			String openId = StringEx.isExEmpty(uid) ? (String) request.getSession().getAttribute(SessionC.OPENID) : uid;
			System.out.println("openId："+openId); 
			if(!StringEx.isExEmpty(openId))
			{
				System.out.println("openId 2"+openId);
				SysReaderWechat srw = readerWechatService.getReaderWechat(openId); 
				if(srw != null && srw.getReader() != null)
				{
					LoginUser user = new LoginUser();
					user.setReader(srw.getReader()); 
					DataResult result = businessService.doQuery(null,user); 
					if(result.getStatus() == DataStatus.OK) 
						map.put("records", result.getMessage());  
					map.put("user", srw.getReader().getReaderName());
				} 
			}
		}catch(Exception ex)
		{
			log.error("查询出现异常："+ex.getMessage());
			map.put("error", "查询错误"); 
		}
		return new ModelAndView(this.getViewPath("query"),map);
	}    
	
	
	/***
	 * 跳转到借阅界面
	 * @return "opQSRwWhh9sCHQejRW4V8SlhkFNI";//
	 * @date 2016-8-11 下午2:03:45
	 */
	@RequestMapping(value={"/checkout"},method = RequestMethod.GET)
	public ModelAndView goCheckout(HttpServletRequest request,HttpServletResponse response,ModelMap model)
	{ 
		System.out.println("BusinessController goCheckout"); 
		ModelAndView view = new ModelAndView(this.getRedirectPath("message"));
		try{ 
			Object openid = request.getSession().getAttribute(SessionC.OPENID);
			System.out.println("openid："+openid); 
			if(openid == null || StringEx.isExEmpty(openid.toString()))  
				model.addAttribute("message", "获取用户权限失败");
			else
			{
				SysReaderWechat srw = readerWechatService.getReaderWechat(openid.toString());
				if(srw != null) 
				{   
					request.getSession().setAttribute("reader", srw.getReader());
					view = new ModelAndView(this.getViewPath("checkout")); 
				}
				else 
				{
					model.addAttribute("message", "请先注册"); 
					view = new ModelAndView(this.getRedirectPath("/wechat/register"));
				}
				JsapiUtil.setJsapiTicket(request,response,openid.toString(),model);
			}
		}catch(Exception ex)
		{  
			log.error("获取用户权限失败: "+ex.getMessage());
			model.addAttribute("message", "获取用户权限失败");
		} 
		return view;
	}  
	
	
	/***
	 * 借阅
	 * @return
	 * @date 2016-8-11 下午2:03:45
	 */
	@RequestMapping(value={"/checkout"},method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public DataResult doCheckout(HttpServletRequest request,@RequestParam String bookid,@RequestParam(required=false,defaultValue="") String cardid)
	{ 
		System.out.println("BusinessController doCheckout");
		log.info("bookid: "+bookid +" cardid: "+cardid);
		SysReader reader = null;
		try{
			reader = (SysReader) request.getSession().getAttribute("reader"); 
			return businessService.doCheckOut(reader, bookid); 
		}catch(Exception ex)
		{  
			log.error("获取用户权限失败: "+ex.getMessage()); 
			return new DataResult(DataStatus.ERROR, "获取用户权限失败: "+ex.getMessage());
		}   
	}  
	

	
	/***
	 * 跳转到续借界面
	 * openid = "opQSRwWhh9sCHQejRW4V8SlhkFNI";//
	 * @return
	 * @date 2016-8-11 下午2:03:45
	 */
	@RequestMapping(value={"/renew"},method = RequestMethod.GET)
	public ModelAndView goRenew(HttpServletRequest request,HttpServletResponse response,ModelMap model)
	{ 
		System.out.println("BusinessController goRenew");
		ModelAndView view = new ModelAndView(this.getRedirectPath("message"));;
		try{
			Object openid = request.getSession().getAttribute(SessionC.OPENID);
			System.out.println("openid："+openid); 
			if(openid == null || StringEx.isExEmpty(openid.toString()))  
				model.addAttribute("message", "获取用户权限失败");
			else
			{
				SysReaderWechat srw = readerWechatService.getReaderWechat(openid.toString());
				if(srw != null) 
				{   
					request.getSession().setAttribute("reader", srw.getReader());
					view = new ModelAndView(this.getViewPath("renew")); 
				} 
				else 
				{
					model.addAttribute("message", "请先注册");   
					view = new ModelAndView(this.getRedirectPath("/wechat/register"));
				}
				JsapiUtil.setJsapiTicket(request,response,openid.toString(),model);
			} 
		}catch(Exception ex)
		{  
			log.error("获取用户权限失败: "+ex.getMessage());
			model.addAttribute("message", "获取用户权限失败");
		} 
		return view; 
	} 
	
	/***
	 * 续借
	 * @return
	 * @date 2016-8-11 下午2:03:45
	 */
	@RequestMapping(value={"/renew"},method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public DataResult doRenew(HttpServletRequest request,@RequestParam String bookid,
			@RequestParam(required=false,defaultValue="") String cardid)
	{ 
		System.out.println("BusinessController doRenew");
		log.info("bookid: "+bookid +" cardid: "+cardid);
		SysReader reader = null;
		try{
			reader = (SysReader) request.getSession().getAttribute("reader"); 
			return businessService.doRenew(reader, bookid); 
		}catch(Exception ex)
		{  
			log.error("获取用户权限失败: "+ex.getMessage()); 
			return new DataResult(DataStatus.ERROR, "获取用户权限失败: "+ex.getMessage());
		}   
	} 
	
	
}
